<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>功能相关性表</title>
    <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css" />

    <style>
        body {
            font-family: Arial, sans-serif;
        }

        .container {
            width: 98%;
            margin: 8px auto 0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 8px;
        }

        table,
        th,
        td {
            border: 1px solid #ddd;
        }

        th,
        td {
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        /* 确保表单项在同一行 */
        #table-list {
            display: flex;
            align-items: center;
            gap: 10px; /* 元素之间的间距 */
            margin-bottom: 10px;
        }

        #table-list .layui-form-item {
            margin-bottom: 0;
        }

        #table-list .layui-inline {
            margin-right: 10px;
        }

        /* 调整下拉框宽度 */
        #table-list .layui-input-inline {
            width: 200px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="layui-form" id="table-list">
            <!-- 添加 layui-inline 类使元素内联显示 -->
            <div class="layui-inline">
                <form class="layui-form" id="filterForm">
                    <div class="layui-form-item">
                        <div class="layui-input-inline">
                            <select name="select_ecu" lay-search>
                                <option value="">选择一个零部件</option>
                            </select>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="filterSubmit">
                                <i class="layui-icon layui-icon-search"></i>确定
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="layui-inline">
                <button class="layui-btn layui-btn-normal" id="exportEcuReqs">
                    <i class="layui-icon layui-icon-download-circle"></i>导出需求(部件)
                </button>
            </div>
            <div class="layui-inline">
                <button class="layui-btn layui-btn-normal" id="exportAllReqs">
                    <i class="layui-icon layui-icon-download-circle"></i>导出全部需求
                </button>
            </div>
        </div>
        <table class="layui-hide" id="securityReqsTable" lay-filter="securityReqsTable"></table>
    </div>

    <script src="/static/js/jquery-3.6.0.min.js"></script>
    <script src="/static/js/layui.js" type="text/javascript" charset="utf-8"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;

            var windowHeight = window.innerHeight;
            var tableHeight = windowHeight - 100; // 减去过滤表单的高度和一些边距

            // 渲染表格
            var tableIns = table.render({
                elem: '#securityReqsTable',
                url: '/get_security_reqs_alloc',
                height: tableHeight,

                {#even: true,#}
                cols: [[
                    { field: 'id', title: 'ID', width: 60, align: 'center', hide: true },
                    { type: 'numbers', title: '序号', width: 60, align: 'center' }, // 添加'序号'列
                    { field: 'type', title: '分类', width: 100, align: 'center' },
                    { field: 'code_or', title: '原始需求编码', width: 110, align: 'center' },
                    { field: 'name_or', title: '原始需求标题', width: 200, align: 'left' },
                    { field: 'desc_or', title: '原始需求描述', width: 230, align: 'center' },
                    { field: 'code_dr', title: '设计需求编码', width: 110, align: 'center' },
                    { field: 'name_dr', title: '设计需求标题', width: 230, align: 'left' },
                    { field: 'desc_dr', title: '设计需求描述', width: 400, align: 'center' },
                    { field: 'tara', title: 'TARA', width: 70, align: 'center' },
                    { field: 'cal', title: 'CAL', width: 70, align: 'center' }
                    {#{ fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150, align: 'center' }#}
                ]]
            });

            // 从后端获取功能域选项
            $.get('/get_ecu_list', function (res) {
                if (res.code === 0) {
                    var $select = $('#filterForm select[name="select_ecu"]');
                    res.data.forEach(function (item) {
                        $select.append('<option value="' + item.id + '">' + item.name + '</option>');
                    });
                    form.render('select'); // 重新渲染下拉框
                } else {
                    layer.msg('获取数据失败：' + res.msg);
                }
            });

            // 监听过滤表单提交事件
            form.on('submit(filterSubmit)', function (data) {
                // 获取过滤条件
                var filterData = data.field;
                // 重新渲染表格，传递过滤参数
                tableIns.reload({
                    where: filterData,
                    page: {
                        curr: 1 // 重新从第 1 页开始
                    }
                });
                return false; // 阻止表单默认提交行为
            });

            // 监听工具条
            table.on('tool(funcRelationTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    layer.open({
                        title: '编辑功能',
                        type: 2,
                        content: '/editFunctionForm?id=' + data.id,
                        area: ['630px', '600px'],
                        btn: ['确认', '取消'],
                        yes: function (index, layero) {
                            var iframeWindow = window['layui-layer-iframe' + index];
                            var submitForm = iframeWindow.document.getElementById('functionForm');
                            var formData = new FormData(submitForm);
                            fetch('/edit_function', {
                                method: 'POST',
                                body: formData
                            })
                            .then(response => response.json())
                            .then(data => {
                                layer.msg(data.msg);
                                table.reload('funcRelationTable');
                                layer.close(index);
                            });
                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                        }
                    });
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除该功能吗？', function (index) {
                        $.post('/delete_function', { id: data.id }, function (res) {
                            if (res.status === 'success') {
                                layer.msg('删除成功');
                                table.reload('funcRelationTable');
                            } else {
                                layer.msg('删除失败');
                            }
                        });
                        layer.close(index);
                    });
                }
            });

            // 导出当前ECU需求按钮点击事件
            $('#exportEcuReqs').on('click', function() {
                var selectedEcuId = $('select[name="select_ecu"]').val();
                if (!selectedEcuId) {
                    layer.msg('请先选择一个零部件', {icon: 2});
                    return;
                }

                layer.load(1, {
                    shade: [0.3, '#000'] // 设置遮罩层的透明度和颜色
                });
                $.ajax({
                    url: '/export_ecu_reqs',
                    method: 'POST',
                    data: { ecu_id: selectedEcuId },
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function(data, status, xhr) {
                        layer.closeAll('loading');
                        
                        // 从响应头中获取文件名
                        const contentDisposition = xhr.getResponseHeader('Content-Disposition');
                        let filename = '安全需求.xlsx'; // 默认文件名
                        
                        if (contentDisposition) {
                            const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
                            if (matches != null && matches[1]) {
                                filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
                            }
                        }
                        
                        // 下载文件
                        const url = window.URL.createObjectURL(new Blob([data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', filename);
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(url);
                    },
                    error: function(xhr, status, error) {
                        layer.closeAll('loading');
                        layer.msg('导出失败：' + error, {icon: 2});
                    }
                });
            });

            // 导出全部需求按钮点击事件
            $('#exportAllReqs').on('click', function() {
                layer.load(2, {
                    shade: [0.3, '#000'] // 设置遮罩层的透明度和颜色
                });
                $.ajax({
                    url: '/export_all_reqs',
                    method: 'GET',
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function(data, status, xhr) {
                        layer.closeAll('loading');
                        console.log('export_all_reqs return success. ',data);
                        // 从响应头中获取文件名
                        const contentDisposition = xhr.getResponseHeader('Content-Disposition');
                        let filename = '全部安全需求.xlsx'; // 默认文件名
                        
                        if (contentDisposition) {
                            const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
                            if (matches != null && matches[1]) {
                                filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
                            }
                        }
                        
                        // 下载文件
                        const url = window.URL.createObjectURL(new Blob([data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', filename);
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(url);
                    },
                    error: function(xhr, status, error) {
                        console.log('export_all_reqs return error. ',xhr, status, error);
                        layer.closeAll('loading');
                        layer.msg('导出失败：' + error, {icon: 2});
                    }
                });
            });
        });

    </script>

    <!-- 工具条模板 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
</body>

</html>